package com.elcom.roaming.common.db;

import java.sql.CallableStatement;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;

import oracle.jdbc.internal.OracleTypes;

import com.elcom.db.DbConnection;
import com.elcom.roaming.common.config.ConfigModule;

public class DBConnectionImpl extends DbConnection{

	public static final String SQL_SEARCH_MSISDN = "{CALL SEARCH_MSISDN(?,?)}"; 
	public static final String SQL_INSERT_IMSI_MSISDN = "{CALL INSERT_IMSI_MSISDN(?,?)}";
	
	private final CallableStatement cstmt_search_msisdn;
	private final CallableStatement cstmt_insert_imsi_msisdn;
	
	public DBConnectionImpl(int idx, DbConnection c) throws SQLException {
		super(idx, c.connection());
		c.connection().setAutoCommit(false);
		
		cstmt_search_msisdn = c.connection().prepareCall(SQL_SEARCH_MSISDN);
		cstmt_insert_imsi_msisdn = c.connection().prepareCall(SQL_INSERT_IMSI_MSISDN);
		
	}

	public String searchMSISDN(String imsi) throws SQLException {
		cstmt_search_msisdn.setString(1, imsi);
		cstmt_search_msisdn.registerOutParameter(2, OracleTypes.VARCHAR);
		cstmt_search_msisdn.execute();
		
		return cstmt_search_msisdn.getString(2);
	}
	
	public void insertIMSI_MSISDN(Map<String, String> map) throws SQLException{
		final int batchSize = ConfigModule.DB_QUERY_BATCH;
		int count = 0;

		for (Entry<String, String> entry : map.entrySet()) {
			cstmt_insert_imsi_msisdn.setString(1, entry.getKey());
			cstmt_insert_imsi_msisdn.setString(2, entry.getValue());
			cstmt_insert_imsi_msisdn.addBatch();

			if (++count % batchSize == 0)
				cstmt_insert_imsi_msisdn.executeBatch();
		}
		
		cstmt_insert_imsi_msisdn.executeBatch();	
		
		commit();
	}

}
